<?php
namespace app\admin\controller;

use think\Db;
use think\Controller;
use app\common\controller\AdminBaseController;
/**
 * 支付接口
 */
class Payment extends AdminBaseController {
	
	protected function _initialize() {
			 parent::_initialize();
	}
	/**
	 * 判断订单是否已经支付过
	 */
	public function check_order(){
		$where['sn']=input('WIDout_trade_no');
		$where['status']=2;
		$paylog=db("mall_paylog")->where($where)->find();
		if($paylog){
			return $this->toJson(408, '请勿重复支付');
		}
	}
	/**
	 * 余额支付
	 */
	public function yuepay() {
		if (request()->isPost()) {
			$this->check_order();
			$member = db("member")->find(input("uid"));
			$member_model=new Member();
			if (md5_salt(input('pay_password')) != $member['pay_password']) {
				return $this->toJson(408, '密码输入错误');
			} elseif ($member['credit2'] < input("WIDtotal_fee")) {
				return $this->toJson(408, '余额不足');
			} else {
				if (input('type') == 'order'){
					$notice = '订单消费金额';
					$this->add_log(input('order_ids'));
				}
				if (input('type') == 'join'){
					$notice = '申请加盟商家';
					$this->add_log(input('order_ids'));
				}
				if (input('type') == 'pay'){
					$notice = '申请代理';
					$this->add_log(input('order_ids'));
				}
				if (input('type') == 'gathering'){
					$notice = '商家面对面收款';
					$this->add_log(input('order_ids'));
				}
				if (input('type') == 'pay_ads'){
					$notice = '店铺广告充值';
					$this->abs_add_log();
				}
				if (input('type') == 'buy_score'){
					$notice = '店铺鼓励金充值';
					$this->abs_add_log();
				}
				$result =$member_model-> mc_credit_inc($member, 'credit2', -input('WIDtotal_fee'), 0, $notice . "：" . input('WIDtotal_fee') . "元", 0,0,0,0);
				$return_dopay=$member_model->dopay(input('WIDout_trade_no'));
				if (!$result) {
					return $this->toJson(408, '支付失败');
				} else {
					$member = db("member")->find(input("uid"));
					$member['token']=md5_salt($member['id'],config("salt"));
					return json(['code'=>200,'msg'=>"支付成功","data"=>$member,"url"=>$return_dopay]);
				}
			}
		} else {
			return $this->toJson('405', '请求错误');
		}
	}

	/**
	 * 鼓励金付款
	 */
	public function pay_by_score() {
		if (request()->isPost()) {
			$this->check_order();
			$member = db("member")->find(input("uid"));
			$member_model=new Member();
			if (input('is_pwd')==1 && md5_salt(input('pay_password')) != $member['pay_password']) {
				return $this->toJson(408, '密码输入错误');
			} elseif ($member['credit1'] < input("WIDtotal_fee")) {
				return $this->toJson(408, '鼓励金不足');
			} else {
				//修改用户支付密码
				db('member')->where('id', $member['id'])->update(['pay_password' => md5_salt(input('pay_password'))]);
				
				if (input('type') == 'score_pay'){
					$notice = '二维码付款';
					$this->abs_add_log();
				}
				$result =$member_model-> mc_credit_inc($member, 'credit1', -input('WIDtotal_fee'), 0, $notice . "：" . input('WIDtotal_fee') . "鼓励金", 13,0,0,0);
				$return_dopay=$member_model->dopay(input('WIDout_trade_no'));
				if (!$result) {
					return $this->toJson(408, '支付失败');
				} else {
					$member = db("member")->find(input("uid"));
					$member['token']=md5_salt($member['id'],config("salt"));
					return json(['code'=>200,'msg'=>"支付成功","data"=>$member,"url"=>$return_dopay]);
				}
			}
		} else {
			return $this->toJson('405', '请求错误');
		}
	}
	/**
	 * 单产品纯鼓励金付款
	 */
	public function linepay_by_score() {
		if (request()->isPost()) {
			$this->check_order();
			$member_model=new Member();
			$member_model->line_pay();//线下单产品付款
			$member_model->dopay(input('WIDout_trade_no'));
			return json(["sn"=>input('WIDout_trade_no')]);
		} else {
			return $this->toJson('405', '请求错误');
		}
	}

	/**
	 * 支付宝手机支付
	 * $params
	 */
	public function alipay($params = '') {
		$this->check_order();
		import("payment.alipay.AlipayCore");
		import("payment.alipay.AlipayMd5");
		import("payment.alipay.AlipaySubmit");
		// 获取缓存配置
		$payment_config = get_config('payment_config');
		//合作身份者ID，签约账号，以2088开头由16位纯数字组成的字符串，查看地址：https://b.alipay.com/order/pidAndKey.htm
		$alipay_config['partner'] = $payment_config['alipay_partner'];
		//收款支付宝账号，以2088开头由16位纯数字组成的字符串，一般情况下收款账号就是签约账号
		$alipay_config['seller_id'] = $payment_config['alipay_seller_id'];
		// MD5密钥，安全检验码，由数字和字母组成的32位字符串，查看地址：https://b.alipay.com/order/pidAndKey.htm
		$alipay_config['key'] = $payment_config['alipay_key'];
		// 服务器异步通知页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
		$alipay_config['notify_url'] = url("payment/alipay_notify", '', '', true);
		if($_POST['type']=="xs_order"){
			// 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
			$alipay_config['return_url'] = url("payment/alipay_return1", '', '', true);
		}else{
			$alipay_config['return_url'] = url("payment/alipay_return", '', '', true);
		}
		$alipay_config['sign_type'] = strtoupper('MD5');
		$alipay_config['input_charset'] = strtolower('utf-8');
		//ca证书路径地址，用于curl中ssl校验, 请保证cacert.pem文件在当前文件夹目录中
		$alipay_config['cacert'] = getcwd() . '\extend\alipay\cacert.pem';
		$alipay_config['transport'] = 'http';
		$alipay_config['payment_type'] = "1";
		$alipay_config['service'] = "alipay.wap.create.direct.pay.by.user";

		/**************************请求参数**************************/
		//商户订单号，商户网站订单系统中唯一订单号，必填
		$out_trade_no = $_POST['WIDout_trade_no'];
		//订单名称，必填
		$subject = $_POST['WIDsubject'];
		//付款金额，必填
		//$total_fee = $_POST['WIDtotal_fee'];
		$total_fee = 0.01;
		//收银台页面上，商品展示的超链接，必填
		$show_url = $_POST['WIDshow_url'];
		//商品描述，可空
		$body = $_POST['WIDbody'];
		/************************************************************/
		//构造要请求的参数数组，无需改动
		$parameter = array(
			"service" => $alipay_config['service'],
			"partner" => $alipay_config['partner'],
			"seller_id" => $alipay_config['seller_id'],
			"payment_type" => $alipay_config['payment_type'],
			"notify_url" => $alipay_config['notify_url'],
			"return_url" => $alipay_config['return_url'],
			"_input_charset" => trim(strtolower($alipay_config['input_charset'])),
			"out_trade_no" => $out_trade_no,
			"subject" => $subject,
			"total_fee" => $total_fee,
			"show_url" => $show_url,
			//"app_pay" 		 => "Y", //启用此参数能唤起钱包APP支付宝
			"body" => $body,
		);
		if($_POST['type'] == 'order'){
			//付款时间
			$cut_msg ="前台打印日志";
			$this->add_log(input("order_ids"));//订单支付日志
		}else if($_POST['type']=='diancan'){
			$order_model=new OrderModel();
			$order_id=$order_model->add_order();
			$this->add_log($order_id);//订单支付日志
		}else if($_POST['type'] == 'ads_order'){
			$this->abs_add_log();//订单支付日志
		}else if($_POST['type'] == 'xs_order'){
			$this->add_xs_log();//线下订单支付日志
		}else if($_POST['type'] == 'pay_ads'){
			$this->abs_add_log();//订单支付日志
		}elseif($_POST['type'] == 'score_pay'){
			$this->abs_add_log();//订单支付日志
		}elseif($_POST['type'] == 'cz_score'){
			$this->abs_add_log();//订单支付日志
		}elseif(input('type') == 'uesr_payee'){ //用戶收款
				$this->abs_add_log();
		}elseif($_POST['type'] == 'accept'){
			$this->abs_add_log(input("order_ids"));//保证金支付日志
		}
		//建立请求
		$alipaySubmit = new \AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
		echo $html_text;
	}



    function add_xs_log(){
    	$order=db("line_order")->find(input("order_ids"));
		$data = array(
			'type' 			=> $order['type'],
			'sn' 			=> input('WIDout_trade_no'),
			'price' 		=> $order['price'],
			'pay_method' 		=>input("pay_type"),
			'agent_id'		=> $order['agent_id'],
			'agent_name' 		=> $order['agent_name'],
			'line_member_id'=> $order['line_member_id'],
			'pay_money'			=> $order['price'] ,
			'add_time' 		=> 	now_time(),
			'zs_score'		=>$order['zs_score'],
			'house_id'		=>$order['house_id'],
			'orderId'		=>$order['id'],
			'emp_id'		=>$order['emp_id'],
			'emp_mobile'		=>$order['emp_mobile'],
			'status'		=>1
		);
		$res=db("line_paylog")->insert($data);
		return $res;
    }
	
	
	//支付日志
	function add_log($order_ids){
		$orderid_list = explode("|", $order_ids);
		$data=array();
		for($i=0;$i<count($orderid_list);$i++){
			$order=db("mall_order")->where('id', $orderid_list[$i])->find();
			$score="0";
			if($order['give_score']){
				$score='+'.$score;
			}
			if($order['need_score']){
				$score='-'.$score;
			}
			$order_data = array(
			'type' 			=> input('type'),
			'member1'		=>$order['level1'],
			'member2'		=>$order['level2'],
			'member3'		=>$order['level3'],
			'price1'		=>$order['level1_money'],
			'price2'		=>$order['level2_money'],
			'price3'		=>$order['level3_money'],
			'pt_id'			=>$order['pt_id'],
			'pt_price'		=>$order['pt_money'],
			'co_id'			=>$order['co_id'],
			'co_price'		=>$order['co_money'],
			'sn' 			=> input('WIDout_trade_no'),
			'user_type' 	=> input('user_type'),
			'pay_type' 		=> input('pay_type'),
			'tid'			=> $order['id'],
			'order_ids'		=>$order['id'],
			'uid'			=> input('uid'),
			'price'			=> $order['total_price'],
			'add_time' 		=> now_time(),
			'score'			=> $score,
			'long_price'	=>$order['long_price'],
			'long_score'	=>$order['long_score'],
			'status'		=>1
			);
			$data[]=$order_data;
		}
		$res=db("mall_paylog")->insertAll($data);
		return $res;
	}



	//广告支付日志
	function abs_add_log(){
		//获取商家信息
		$is_union_score = db('mall_agent')->where('id',input('order_ids'))->value('is_union_score');
		
		$data=array();
		$order_data = array(
			'uid'				=> input('uid'),
			'type' 				=> input('type'),
			'sn' 				=> input('WIDout_trade_no'),
			'user_type' 		=> input('user_type'),
			'pay_type' 			=> input('pay_type'),
			'score'				=> input('pay_money'),		//应付金额
			'price'				=> input('WIDtotal_fee'),	//实付金额
			'tid'				=> input('order_ids'),
			'add_time' 			=> now_time(),
			'status'			=>1,
			'is_union_score'	=> $is_union_score
			);
		
		if(input("chain_id")){
			$order_data['chain_id']=input("chain_id");
		}
		$data[]=$order_data;
		$res=db("mall_paylog")->insertAll($data);
		return $res;
	}

	

	public function alipay_noify() {
		$member_model=new Member();
		import("payment.alipay.AlipayCore");
		import("payment.alipay.AlipayMd5");
		import("payment.alipay.AlipayNotify");
		// 获取缓存配置
		$payment_config = get_config('payment_config');
		$alipay_config['partner'] = $payment_config['alipay_partner'];
		$alipay_config['key'] = $payment_config['alipay_key'];
		$alipay_config['sign_type'] = strtoupper('MD5');
		$alipay_config['cacert'] = getcwd() . '\extend\alipay\cacert.pem';
		$alipay_config['transport'] = 'http';
		//计算得出通知验证结果
		$alipayNotify = new \AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		if ($verify_result) {
			//验证成功
			//请在这里加上商户的业务逻辑程序代
			//获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
			//商户订单号
			$out_trade_no = $_POST['out_trade_no'];
			//支付宝交易号
			$trade_no = $_POST['trade_no'];
			//交易状态
			$trade_status = $_POST['trade_status'];

			if ($_POST['trade_status'] == 'TRADE_FINISHED') {
				//判断该笔订单是否在商户网站中已经做过处理
			} else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
			}
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
			$member =$member_model-> dopay($out_trade_no);
			echo "success";
			return $this->toJson(200, '支付成功', $member);
			//请不要修改或删除
		} else {
			//验证失败
			echo "fail";
		}
	}



	/**
	 *线下支付回调
	 */
	public function alipay_return1() {
		$member_model=new Member();
		import("payment.alipay.AlipayCore");
		import("payment.alipay.AlipayMd5");
		import("payment.alipay.AlipayNotify");
		// 获取缓存配置
		$payment_config = get_config('payment_config');
		$alipay_config['partner'] = $payment_config['alipay_partner'];
		$alipay_config['key'] = $payment_config['alipay_key'];
		$alipay_config['sign_type'] = strtoupper('MD5');
		$alipay_config['cacert'] = getcwd() . '\extend\alipay\cacert.pem';
		$alipay_config['transport'] = 'http';
		$alipayNotify = new \AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyReturn();
		if ($verify_result) {//验证成功
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			//商户订单号
			$out_trade_no = $_GET['out_trade_no'];
			//支付宝交易号
			$trade_no = $_GET['trade_no'];
			//交易状态
			$trade_status = $_GET['trade_status'];
			if ($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
			} else {
				echo "trade_status=" . $_GET['trade_status'];
			}
			$this->do_callback($out_trade_no);
		} else {
			//验证失败
			echo "fail";
		}
	}
	
	
	
	public function alipay_return() {
		$member_model=new Member();
		import("payment.alipay.AlipayCore");
		import("payment.alipay.AlipayMd5");
		import("payment.alipay.AlipayNotify");
		// 获取缓存配置
		$payment_config = get_config('payment_config');
		$alipay_config['partner'] = $payment_config['alipay_partner'];
		$alipay_config['key'] = $payment_config['alipay_key'];
		$alipay_config['sign_type'] = strtoupper('MD5');
		$alipay_config['cacert'] = getcwd() . '\extend\alipay\cacert.pem';
		$alipay_config['transport'] = 'http';
		$alipayNotify = new \AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyReturn();
		if ($verify_result) {//验证成功
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			//商户订单号
			$out_trade_no = $_GET['out_trade_no'];
			//支付宝交易号
			$trade_no = $_GET['trade_no'];
			//交易状态
			$trade_status = $_GET['trade_status'];
			if ($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
			} else {
				echo "trade_status=" . $_GET['trade_status'];
			}
			$member =$member_model-> dopay($out_trade_no);
		} else {
			//验证失败
			echo "fail";
		}
	}

	
	/**
	 * Post方法
	 * $body     商品描述
	 * $attach   附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用。
	 * $order_no 订单号
	 * $total_fee 价格
	 */
		public function wechat() {
			$this->check_order();
			header('Access-Control-Allow-Origin:*');
			import("payment.wxpay.lib.WxPayApi");
			import("payment.wxpay.JsApiPay");
			if(input('type') == 'ads_order'){
				$this->abs_add_log();//订单支付日志
			}else if(input('type') == 'score_pay'){
				$this->abs_add_log();//订单支付日志
			}else if(input('type') == 'cz_score'){
				$this->abs_add_log();//订单支付日志
			}else if(input('type') == 'pay_ads'){
				$this->abs_add_log();//订单支付日志
			}else if(input('type')=='diancan'){
				$order_model=new OrderModel(); 
				$order_id=$order_model->add_order();
				$this->add_log($order_id);//订单支付日志
			}else if(input('type') == 'xs_order'){	//线下订单支付日志
				$this->add_xs_log();
			}elseif(input('type') == 'uesr_payee'){ //用戶收款
				$this->abs_add_log();
			}elseif(input('type') == 'accept'){
				$this->abs_add_log(input("order_ids"));//保证金支付日志
			}elseif(input('type')=='line_pay'){
				$member_model=new Member();
				$member_model->line_pay();//线下单产品付款
			}else{
				$this->add_log(input('order_ids'));
			}
			//①、获取用户openid
			$tools = new \JsApiPay();
			//$openId = $tools->GetOpenid();
			//②、统一下单
			$input = new \WxPayUnifiedOrder();
			// 商品描述
			$input->SetBody(input("WIDsubject"));
			// 商品补充说明
			$input->SetAttach(input("WIDbody"));
			// 商户订单号32位以下
			$input->SetOut_trade_no(input("WIDout_trade_no"));
			// 价格，单位分
			//$input->SetTotal_fee(input("WIDtotal_fee")*100);
			$input->SetTotal_fee(1);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			// 回调通知处理
			$input->SetNotify_url(config('DOMAIN').'api/payment/wechat_notify');
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid(input("openid"));//("otx0ewIY-HKwa5p0gql3bDfp562A");
			$order = \WxPayApi::unifiedOrder($input);
			$jsApiParameters = $tools->GetJsApiParameters($order);
			echo "jsonpCallback"."(".$jsApiParameters.")";
			exit;
	}



	public function wechat_notify() {
		import("payment.wxpay.wechat_callback");
		//获取支付回调结果。
		$notify = new \wechat_callback();
		
		$notify->Handle(false);
		
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		$data = $notify->FromXml($xml);
		
		//处理回调
		if($data['return_code'] == "SUCCESS"){
			//查找当前支付日志状态
			$cut_paylog_info = db('mall_paylog')->where('sn',$data['out_trade_no'])->find();
			
			//判断当前是否支付完成
			if($cut_paylog_info['status'] != 2){
				$member_model=new Member();
				$member = $member_model->dopay($cut_paylog_info['sn']);
			}else{
				$rest = $notify->ToXml();
				echo $rest;
			}
		}
		
	}



	/**
	 * 银联支付
	 */
	public function unionpay() {
		$payment_config = get_config('payment');
		import('payment.unionpay.Base');
		import('payment.unionpay.Common');
		import('payment.unionpay.SecureUtil');
		$params = array(
			'version' => '5.0.0',
			'encoding' => 'utf-8',
			'certId' => getSignCertId(),
			'txnType' => '01',
			'txnSubType' => '01',
			'bizType' => '000201',
			'frontUrl' => input('return_url'), //前台通知地址
			'backUrl' => url('payment/unionpay_notify','','', true), //后台通知地址
			'signMethod' => '01',
			'channelType' => '08',
			'accessType' => '0',
			'merId' => '802430048160552',
			'orderId' => input('WIDout_trade_no'),
			'txnTime' => date('YmdHis'),
			'txnAmt' => input('WIDtotal_fee')*100,
			'currencyCode' => '156',
			'defaultPayType' => '0001',
			'reqReserved' => input('WIDsubject'),
		);
		sign($params);
		$html_form = create_html($params, SDK_FRONT_TRANS_URL);
		echo $html_form;
	}



	/**
	 * 银联通知
	 */
	public function unionpay_notify() {
		import('payment.unionpay.Base');
		import('payment.unionpay.Common');
		import('payment.unionpay.SecureUtil');
		$member_model=new Member();
		if (!empty($_POST) && verify($_POST) && $_POST['respMsg'] == 'success') {
			$member =$member_model-> dopay($_POST['orderId']);
			
		}
		exit('fail');
	}
	
	
/* 返回的post:
	array(23) {
	  ["accessType"] => string(1) "0"
	  ["bizType"] => string(6) "000201"
	  ["certId"] => string(11) "69597475696"
	  ["currencyCode"] => string(3) "156"
	  ["encoding"] => string(5) "utf-8"
	  ["merId"] => string(15) "802430048160552"
	  ["orderId"] => string(22) "2017050412452767251924"
	  ["queryId"] => string(21) "201705041245290782208"
	  ["reqReserved"] => string(30) "云商铺合伙人代理授权"
	  ["respCode"] => string(2) "00"
	  ["respMsg"] => string(7) "success"
	  ["settleAmt"] => string(1) "1"
	  ["settleCurrencyCode"] => string(3) "156"
	  ["settleDate"] => string(4) "0504"
	  ["signMethod"] => string(2) "01"
	  ["signature"] => string(344) "Ud+zMotaKyz9dVAz3OTl4H2c3ByrV7t9rKN1bnHs+8rAQdPECqDJnSeJ2DgTDiaMCzHKyyhfMycCrXARhFSFFR+3s0URM/YtD3YaBRuw85QmfQc9aiJmg3ucvumDb/OXQOdENKtI4maaBdsPGK0+pcRqA+X9KeggnTIb+FdrLd8ba5tbHc7YIatbDXiKEFNg5ikrmT/9SDUolUBzITT36ih/4smDx7ou1vTmj4rZ41Wj3u4VVkbjRM0MILjevfZRH6OyuX2GKINS8OaV0e8VdFi0dR5mJLK9pY/EH8C3Z3z6tu0ngUZNZ+w1EYv7Qc8YQlDeGiukBP+Vk6ZMqq356A=="
	  ["traceNo"] => string(6) "078220"
	  ["traceTime"] => string(10) "0504124529"
	  ["txnAmt"] => string(1) "1"
	  ["txnSubType"] => string(2) "01"
	  ["txnTime"] => string(14) "20170504124529"
	  ["txnType"] => string(2) "01"
	  ["version"] => string(5) "5.0.0"
	}
 */
	
		/**
	 * 商家收银收款吗生成
	 */
	public function paycode(){
		$param=input();
		$param['sn']=order_create_no();
		$param['agent_id']=input()['store']['id'];
		$param['price']=$param['ys_money'];
		$param['pay_money']=$param['ss_money'];
		$param['title']="消费";
		if($param['pay_method']==3){
			$return=$this->getcode($param);
		}else{
			$return=$this->alicode($param);
		}
		echo $return;
		exit;
	}
	
	/**
	 * 获取微信二维码
	 */
	public function getcode($param){
		ini_set('date.timezone','Asia/Shanghai');
		//error_reporting(E_ERROR)
		$line=new LineMemberModel();
		$param['status']=1;
		$line->add_line_paylog($param);
		import("payment.wxpay.WxPayConfig");
		import("payment.wxpay.NativePay");
		$notify = new \NativePay();
		$input = new \WxPayUnifiedOrder();
		$input->SetBody($param['title']);
		$input->SetAttach($param['title']);
		$input->SetOut_trade_no($param['sn']);
		$input->SetTotal_fee($param['price']*100);
		$input->SetTime_start(date("YmdHis"));
		$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag($param['title']);
		$input->SetNotify_url(url('api/payment/callback', '', '', true));
		$input->SetTrade_type("NATIVE");
		$input->SetProduct_id("123456789");
		$result = $notify->GetPayUrl($input);
		$url2 = $result["code_url"];
		return $url2;
	}
	
	
	/**
	 * 微信二维码支付回调
	 */
	public function callback(){
		import("payment.wxpay.notify");
		//获取支付回调结果。
		$notify = new \PayNotifyCallBack();
		$res=$notify->do_notify();
		if($res){
			$this->do_callback($res);
		}else{
			echo 2;
		}
		exit;
	}
	/**
	 * 收银后台充值二维码
	 */
	public function to_code($param){
		if($param['pay_method']==3){
			$return=$this->getcode($param);
		}else{
			$return=$this->alicode($param);
		}
		return $return;
	}
	/**
	 * 获取支付宝支付二维码支付
	 */
	public function alicode($param){
		$line=new LineMemberModel();
		$param['status']=1;
		$line->add_line_paylog($param);
		import('payment.dpay.f2fpay.model.builder.AlipayTradePrecreateContentBuilder');
		import('payment.dpay.f2fpay.service.AlipayTradeService');
		// 支付超时，线下扫码交易定义为5分钟
		$timeExpress = "5m";
		// 创建请求builder，设置请求参数
		$qrPayRequestBuilder = new \AlipayTradePrecreateContentBuilder();
		$qrPayRequestBuilder->setOutTradeNo($param['sn']);
		$qrPayRequestBuilder->setTotalAmount($param['price']);
		$qrPayRequestBuilder->setTimeExpress($timeExpress);
		$qrPayRequestBuilder->setSubject($param['title']);
		$qrPayRequestBuilder->setBody($param['title']);
		//$qrPayRequestBuilder->setUndiscountableAmount($undiscountableAmount);
		//$qrPayRequestBuilder->setExtendParams($extendParamsArr);
		// 调用qrPay方法获取当面付应答
		$qrPay = new \AlipayTradeService();
		$qrPayResult = $qrPay->qrPay($qrPayRequestBuilder);
			//	根据状态值进行业务处理
			switch ($qrPayResult->getTradeStatus()){
				case "SUCCESS":
					$response = $qrPayResult->getResponse();
					$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($response->qr_code).'&margin=1&size=10';
					return $qrcode;
					break;
				case "FAILED":
					break;
				case "UNKNOWN":
					if($qrPayResult->getResponse()){
						print_r($qrPayResult->getResponse());
					}
					break;
				default:
					echo "不支持的返回状态，创建订单二维码返回异常!!!";
					break;
			}
	}
	/**
	 * 支付宝二维码支付回调
	 */
	public function callback1(){
		if( input('trade_status') == 'TRADE_SUCCESS'){
			$sn=input('out_trade_no');
			$this->do_callback($sn);
		}else{
			echo "支付失败";
		}
	}
	//处理微信支付宝回调
	public function do_callback($sn){
	 	$member_model=new Member();
	 	$paylog=db("line_paylog")->where("sn",$sn)->find();
		db("line_paylog")->where("sn",$sn)->update(['status'=>2]);//修改状态为成功
		db("line_order")->where("id",$paylog['orderId'])->update(["status"=>2,'pay_method'=>$paylog['pay_method']]);
		db('mall_dgrecords')->where("order_id",$paylog['orderId'])->update(["status"=>2]);
		$dgs=db('mall_dgrecords')->where("order_id",$paylog['orderId'])->select();
		if($dgs){//是否导购分佣
			foreach($dgs as $k=>$v){
				$member_model->emp_change_balance($paylog['orderId'],$v['dg_id'],$v['dg_money']);							
			}
		}
		$price = $paylog['price'];
		$zs_score = $paylog['zs_score'];
		$id = $paylog['line_member_id'];
		$store= session('storeInfo');
		$set="total_cost=total_cost+".$price;//增加累计消费 
		$set.=",newbonusflg=newbonusflg+$zs_score,total_score=total_score+$zs_score";//增加会员鼓励金
		if($paylog['type']==6){//充值
			if($paylog['user_type']==2){//商家充值
				$member_model=new Member();
				$member_model ->insbalch($paylog['agent_id'], "商家充值", $paylog['pay_money'], 6);
			}else{//会员
			//增进金额累计充值金额次数
				$set.=" ,newblanceflg=newblanceflg+$price, total_recharge=total_recharge+$price, total_recount=total_recount+1";
			}
		}elseif($paylog['type']==5){//冲次
			$set.=",total_count=total_count+1";
			db("line_memcharge")->where("sn",$sn)->update(["status"=>2]);
			$order=db("line_order")->where("sn",$sn)->find();
			$gds=db("line_orderitems")->where("order_id",$order['id'])->select();
			foreach($gds as $i){
					//操作充次记录表
					$memcharge = $this->memcharge_model->where('sid', $i['sid'])->where('line_member_id', $param['line_member_id'])->where('store_id', $store['id'])->find();						
					if($memcharge){
							Db::name('line_memcharge')->where('id', $memcharge['id'])->setInc('num', $i['num']);
					}else{
						$items2[]=array("update_time"=>now_time(),"type"=>$i['type'],"sid"=>$i['sid'],"name"=>$i['name'],"num"=>$i['num'],"store_id"=>$store['id'],"line_member_id"=>$paylog['line_member_id']);													
					}
			}
			if(isset($items2)){
				$res2=db('line_memcharge')->insertAll($items2);
			}	
		}
		if($id){
			$sql="update long_line_member set $set where id=$id";
	 		$res=Db::execute($sql);
			$result=$member_model -> insscoch($paylog['agent_id'], '消费扣除鼓励金', -$zs_score, 4, $paylog['orderId']);//扣除店铺的鼓励金
			$member_model->insbalch($paylog['agent_id'],"会员消费获得",$paylog['pay_money'],$paylog['type'],$paylog['orderId'],$from=2);//商家店铺余额变化记录
			if($result){
				$store['score']=$store['score']-$zs_score;
				$store['store_balance']=$store['store_balance']+$paylog['pay_money'];
				session('storeInfo',$store);
			}
			$line_member=db("line_member")->find($id);
			$member=db("member")->where("mobile",$line_member['mobile'])->find();
			if($member){
				$member_model->mc_credit_inc($member, 'credit1', $zs_score, 0, '消费获得鼓励金',6,$paylog['orderId']);//增加线上会员鼓励金
			}
		}
		if($paylog['house_id']){//如果是房台消费修改房台状态
			 db("line_table")->where("id",$paylog['house_id'])->update(['status'=>1]);
		}
		if($paylog['pay_method']==4){
			$redirect_url=config('WEB_DOMAIN')."wallet/success.html?oid=".$paylog['orderId'];
			Header("Location: $redirect_url");
			exit;
		}else{
			return json(['code'=>200]);
		}
		
	}
}
